import { NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';
import { z } from 'zod';

const siteSchema = z.object({
  name: z.string().min(2),
  contractAmount: z.number().positive(),
  status: z.enum(['active', 'completed', 'paused'])
});

// GET /api/sites - 获取工地列表
export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const status = searchParams.get('status') as 'active' | 'completed' | 'paused' | null;

  const where = status ? { status } : undefined;
  const sites = await prisma.site.findMany({
    where,
    include: {
      expenses: {
        select: {
          amount: true
        }
      },
      _count: {
        select: { expenses: true }
      }
    },
    orderBy: {
      createdAt: 'desc'
    }
  });
  return NextResponse.json(sites);
}

// POST /api/sites - 创建新工地
export async function POST(request: Request) {
  try {
    const data = await request.json();
    const validation = siteSchema.safeParse(data);

    if (!validation.success) {
      return NextResponse.json(
        { error: validation.error.errors },
        { status: 400 }
      );
    }

    const site = await prisma.site.create({
      data: validation.data
    });

    return NextResponse.json(site);
  } catch (error: unknown) {
    console.error('Failed to create site:', error);
    return NextResponse.json(
      { error: 'Failed to create site' },
      { status: 500 }
    );
  }
}

// PUT /api/sites/[siteId] - 更新工地
export async function PUT(request: Request) {
  try {
    const siteId = request.url.split('/').pop();
    const data = await request.json();
    const validation = siteSchema.partial().safeParse(data);

    if (!validation.success) {
      return NextResponse.json(
        { error: validation.error.errors },
        { status: 400 }
      );
    }

    const site = await prisma.site.update({
      where: { id: siteId },
      data: validation.data
    });

    return NextResponse.json(site);
  } catch (error: unknown) {
    console.error('Failed to update site:', error);
    if (error instanceof Error && error.message.includes('Record to update not found')) {
      return NextResponse.json(
        { error: 'Site not found' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: 'Failed to update site' },
      { status: 500 }
    );
  }
}

// DELETE /api/sites/[siteId] - 删除工地
export async function DELETE(request: Request) {
  try {
    const siteId = request.url.split('/').pop();
    const site = await prisma.site.delete({
      where: { id: siteId }
    });

    return NextResponse.json(site);
  } catch (error: unknown) {
    console.error('Failed to delete site:', error);
    if (error instanceof Error && error.message.includes('Record to delete does not exist')) {
      return NextResponse.json(
        { error: 'Site not found' },
        { status: 404 }
      );
    }
    return NextResponse.json(
      { error: 'Failed to delete site' },
      { status: 500 }
    );
  }
}